package com.gw.vip.server.service.dao_service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gw.vip.common.constants.VipConstants;
import com.gw.vip.common.exception.ServiceException;
import com.gw.vip.common.util.Snowflake;
import com.gw.vip.server.dao.BatchClearLedgerMapper;
import com.gw.vip.server.po.BatchClearLedger;
import com.gw.vip.server.po.HisClearLedger;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author GW
 * @description
 * @since 2022-05-10
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class BatchClearLedgerService extends ServiceImpl<BatchClearLedgerMapper, BatchClearLedger> {

    private final BatchClearLedgerMapper mapper;
    private final Snowflake snowflake;
    private final HisClearLedgerService hisClearLedgerService;

    public BatchClearLedger getByBase(String capitalId) {
        return this.mapper.getByBase(capitalId);
    }

    public BatchClearLedger init(BatchClearLedger clearLedger, LocalDate clearDate) {
        BatchClearLedger clearLedgerNew = new BatchClearLedger();
        BeanUtils.copyProperties(clearLedger, clearLedgerNew);
        clearLedgerNew.setId(snowflake.nextStringId());
        clearLedgerNew.setLastAmt(BigDecimal.ZERO);
        clearLedgerNew.setDiffAmt(clearLedger.getAmt());
        clearLedgerNew.setClearDate(clearDate);
        LocalDateTime now = LocalDateTime.now();
        clearLedgerNew.setCrtTime(now);
        clearLedgerNew.setCrtName(VipConstants.SYS);
        clearLedgerNew.setUpdTime(now);
        clearLedgerNew.setUpdName(VipConstants.SYS);
        return clearLedgerNew;
    }

    public void toHis() {
        List<BatchClearLedger> clearLedgerList = this.list();
        for (BatchClearLedger clearLedger:clearLedgerList){
            HisClearLedger hisClearLedger = new HisClearLedger();
            BeanUtils.copyProperties(clearLedger, hisClearLedger);
            hisClearLedger.setId(snowflake.nextStringId());
            if (!hisClearLedgerService.save(hisClearLedger)){
                log.error("保存总账数据失败！");
                throw new ServiceException("保存总账数据失败!");
            }
        }
    }

    public void updateLastAmt() {
        this.mapper.updateLastAmt();
    }
}
